import React, { useState, useEffect } from 'react';
import './AdminPanel.css';
import apiConfig from '../config/api.js';
import authService from '../services/authService.js';

const AdminPanel = ({ onClose, currentUser }) => {
  const [activeTab, setActiveTab] = useState('statistics');
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  // 权限检查
  const isAdmin = currentUser?.role === 'admin';
  
  // 如果不是管理员，显示权限不足信息
  if (!isAdmin) {
    return (
      <div className="admin-panel-overlay">
        <div className="admin-panel">
          <div className="admin-header">
            <h2>权限不足</h2>
            <button className="close-btn" onClick={onClose}>✕</button>
          </div>
          <div className="admin-content">
            <div className="permission-denied">
              <div className="permission-icon">🚫</div>
              <h3>访问被拒绝</h3>
              <p>您没有权限访问管理员面板。</p>
              <p>请联系系统管理员获取相应权限。</p>
              <button className="close-button" onClick={onClose}>
                关闭
              </button>
            </div>
          </div>
        </div>
      </div>
    );
  }
  const [statistics, setStatistics] = useState(null);
  const [users, setUsers] = useState([]);
  const [loginRecords, setLoginRecords] = useState({ items: [], total: 0, page: 1, total_pages: 0 });
  const [processingRecords, setProcessingRecords] = useState({ items: [], total: 0, page: 1, total_pages: 0 });
  const [searchTerm, setSearchTerm] = useState('');
  const [currentPage, setCurrentPage] = useState(1);
  const [filters, setFilters] = useState({
    user_id: '',
    username: '',
    start_date: '',
    end_date: '',
    status: '',
    operation_type: ''
  });

  // 获取认证token
  const getAuthHeaders = () => {
    const token = authService.getToken();
    return {
      'Authorization': `Bearer ${token}`,
      'Content-Type': 'application/json'
    };
  };

  // 获取完整的API URL
  const getApiUrl = (endpoint) => {
    return apiConfig.getApiURL(endpoint);
  };

  // 获取系统统计信息
  const fetchStatistics = async () => {
    setLoading(true);
    try {
      const response = await fetch(apiConfig.getAdminURL('/statistics'), {
        headers: getAuthHeaders()
      });
      
      if (response.ok) {
        const data = await response.json();
        setStatistics(data);
      } else if (response.status === 403) {
        setError('权限不足：您没有访问管理员功能的权限');
      } else {
        setError('获取统计信息失败');
      }
    } catch (error) {
      setError('获取统计信息失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取用户列表
  const fetchUsers = async () => {
    setLoading(true);
    try {
      const searchParam = searchTerm ? `&search=${encodeURIComponent(searchTerm)}` : '';
      const response = await fetch(apiConfig.getAdminURL(`/users?skip=${(currentPage - 1) * 20}&limit=20${searchParam}`), {
        headers: getAuthHeaders()
      });
      
      if (response.ok) {
        const data = await response.json();
        setUsers(data);
      } else if (response.status === 403) {
        setError('权限不足：您没有访问用户管理的权限');
      } else {
        setError('获取用户列表失败');
      }
    } catch (error) {
      setError('获取用户列表失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取登录记录
  const fetchLoginRecords = async () => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: currentPage,
        page_size: 20,
        ...Object.fromEntries(Object.entries(filters).filter(([_, value]) => value))
      });
      
      const response = await fetch(apiConfig.getAdminURL(`/login-records?${queryParams}`), {
        headers: getAuthHeaders()
      });
      
      if (response.ok) {
        const data = await response.json();
        setLoginRecords(data);
      } else if (response.status === 403) {
        setError('权限不足：您没有访问登录记录的权限');
      } else {
        setError('获取登录记录失败');
      }
    } catch (error) {
      setError('获取登录记录失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 获取数据处理记录
  const fetchProcessingRecords = async () => {
    setLoading(true);
    try {
      const queryParams = new URLSearchParams({
        page: currentPage,
        page_size: 20,
        ...Object.fromEntries(Object.entries(filters).filter(([_, value]) => value))
      });
      
      const response = await fetch(apiConfig.getAdminURL(`/processing-records?${queryParams}`), {
        headers: getAuthHeaders()
      });
      
      if (response.ok) {
        const data = await response.json();
        setProcessingRecords(data);
      } else if (response.status === 403) {
        setError('权限不足：您没有访问处理记录的权限');
      } else {
        setError('获取处理记录失败');
      }
    } catch (error) {
      setError('获取处理记录失败: ' + error.message);
    } finally {
      setLoading(false);
    }
  };

  // 更新用户状态
  const updateUserStatus = async (userId, isActive) => {
    try {
      const response = await fetch(getApiUrl(`/api/admin/users/${userId}/status`), {
        method: 'PATCH',
        headers: getAuthHeaders(),
        body: JSON.stringify({ is_active: isActive })
      });
      
      if (response.ok) {
        fetchUsers(); // 重新加载用户列表
      } else if (response.status === 403) {
        setError('权限不足：您没有修改用户状态的权限');
      } else {
        const errorData = await response.json().catch(() => ({}));
        setError(errorData.detail || '更新用户状态失败');
      }
    } catch (error) {
      setError('更新用户状态失败: ' + error.message);
    }
  };

  // 更新用户角色
  const updateUserRole = async (userId, role) => {
    try {
      const response = await fetch(getApiUrl(`/api/admin/users/${userId}/role`), {
        method: 'PATCH',
        headers: getAuthHeaders(),
        body: JSON.stringify({ role })
      });
      
      if (response.ok) {
        fetchUsers(); // 重新加载用户列表
      } else if (response.status === 403) {
        setError('权限不足：您没有修改用户角色的权限');
      } else {
        const errorData = await response.json().catch(() => ({}));
        setError(errorData.detail || '更新用户角色失败');
      }
    } catch (error) {
      setError('更新用户角色失败: ' + error.message);
    }
  };

  // 标签页切换处理
  useEffect(() => {
    setError('');
    setCurrentPage(1);
    
    switch (activeTab) {
      case 'statistics':
        fetchStatistics();
        break;
      case 'users':
        fetchUsers();
        break;
      case 'login-records':
        fetchLoginRecords();
        break;
      case 'processing-records':
        fetchProcessingRecords();
        break;
    }
  }, [activeTab]);

  // 搜索和分页处理
  useEffect(() => {
    if (activeTab === 'users') {
      fetchUsers();
    } else if (activeTab === 'login-records') {
      fetchLoginRecords();
    } else if (activeTab === 'processing-records') {
      fetchProcessingRecords();
    }
  }, [currentPage, searchTerm, filters]);

  const handleFilterChange = (key, value) => {
    setFilters(prev => ({ ...prev, [key]: value }));
    setCurrentPage(1);
  };

  const formatDateTime = (dateString) => {
    return new Date(dateString).toLocaleString('zh-CN');
  };

  const formatDuration = (durationMs) => {
    if (!durationMs) return '-';
    if (durationMs < 1000) return `${durationMs}ms`;
    return `${(durationMs / 1000).toFixed(2)}s`;
  };

  return (
    <div className="admin-panel-overlay">
      <div className="admin-panel">
        <div className="admin-header">
          <h2>管理员面板</h2>
          <button className="close-btn" onClick={onClose}>✕</button>
        </div>

        {error && (
          <div className="error-message">
            <span>⚠️ {error}</span>
            <button onClick={() => setError('')}>✕</button>
          </div>
        )}

        <div className="admin-tabs">
          <button 
            className={`tab ${activeTab === 'statistics' ? 'active' : ''}`}
            onClick={() => setActiveTab('statistics')}
          >
            统计概览
          </button>
          <button 
            className={`tab ${activeTab === 'users' ? 'active' : ''}`}
            onClick={() => setActiveTab('users')}
          >
            用户管理
          </button>
          <button 
            className={`tab ${activeTab === 'login-records' ? 'active' : ''}`}
            onClick={() => setActiveTab('login-records')}
          >
            登录记录
          </button>
          <button 
            className={`tab ${activeTab === 'processing-records' ? 'active' : ''}`}
            onClick={() => setActiveTab('processing-records')}
          >
            处理记录
          </button>
        </div>

        <div className="admin-content">
          {loading && <div className="loading">加载中...</div>}

          {/* 统计概览 */}
          {activeTab === 'statistics' && statistics && (
            <div className="statistics-grid">
              <div className="stat-card">
                <h3>用户统计</h3>
                <div className="stat-item">
                  <span>总用户数:</span>
                  <span>{statistics.users.total}</span>
                </div>
                <div className="stat-item">
                  <span>活跃用户:</span>
                  <span>{statistics.users.active}</span>
                </div>
                <div className="stat-item">
                  <span>管理员:</span>
                  <span>{statistics.users.admin}</span>
                </div>
              </div>
              
              <div className="stat-card">
                <h3>活动统计</h3>
                <div className="stat-item">
                  <span>7天内登录:</span>
                  <span>{statistics.activity.recent_logins_7d}</span>
                </div>
                <div className="stat-item">
                  <span>24小时处理:</span>
                  <span>{statistics.activity.recent_processing_24h}</span>
                </div>
                <div className="stat-item">
                  <span>今日失败登录:</span>
                  <span>{statistics.activity.failed_logins_today}</span>
                </div>
              </div>
            </div>
          )}

          {/* 用户管理 */}
          {activeTab === 'users' && (
            <div className="users-section">
              <div className="search-bar">
                <input
                  type="text"
                  placeholder="搜索用户名、邮箱或医院..."
                  value={searchTerm}
                  onChange={(e) => setSearchTerm(e.target.value)}
                />
              </div>
              
              <div className="users-table">
                <table>
                  <thead>
                    <tr>
                      <th>用户名</th>
                      <th>邮箱</th>
                      <th>医院</th>
                      <th>职位</th>
                      <th>角色</th>
                      <th>状态</th>
                      <th>注册时间</th>
                      <th>操作</th>
                    </tr>
                  </thead>
                  <tbody>
                    {users.map(user => (
                      <tr key={user.id}>
                        <td>{user.username}</td>
                        <td>{user.email}</td>
                        <td>{user.hospital}</td>
                        <td>{user.position}</td>
                        <td>
                          <select
                            value={user.role}
                            onChange={(e) => updateUserRole(user.id, e.target.value)}
                            disabled={user.username === 'admin'}
                          >
                            <option value="user">普通用户</option>
                            <option value="admin">管理员</option>
                          </select>
                        </td>
                        <td>
                          <span className={`status ${user.is_active ? 'active' : 'inactive'}`}>
                            {user.is_active ? '活跃' : '禁用'}
                          </span>
                        </td>
                        <td>{formatDateTime(user.created_at)}</td>
                        <td>
                          <button
                            onClick={() => updateUserStatus(user.id, !user.is_active)}
                            disabled={user.username === 'admin'}
                            className={`action-btn ${user.is_active ? 'disable' : 'enable'}`}
                          >
                            {user.is_active ? '禁用' : '启用'}
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          )}

          {/* 登录记录 */}
          {activeTab === 'login-records' && (
            <div className="records-section">
              <div className="filters">
                <input
                  type="text"
                  placeholder="用户名"
                  value={filters.username}
                  onChange={(e) => handleFilterChange('username', e.target.value)}
                />
                <input
                  type="date"
                  placeholder="开始日期"
                  value={filters.start_date}
                  onChange={(e) => handleFilterChange('start_date', e.target.value)}
                />
                <input
                  type="date"
                  placeholder="结束日期"
                  value={filters.end_date}
                  onChange={(e) => handleFilterChange('end_date', e.target.value)}
                />
                <select
                  value={filters.status}
                  onChange={(e) => handleFilterChange('status', e.target.value)}
                >
                  <option value="">所有状态</option>
                  <option value="success">成功</option>
                  <option value="failed">失败</option>
                </select>
              </div>
              
              <div className="records-table">
                <table>
                  <thead>
                    <tr>
                      <th>用户名</th>
                      <th>登录时间</th>
                      <th>IP地址</th>
                      <th>用户代理</th>
                      <th>状态</th>
                    </tr>
                  </thead>
                  <tbody>
                    {loginRecords.items.map(record => (
                      <tr key={record.id}>
                        <td>{record.username}</td>
                        <td>{formatDateTime(record.login_time)}</td>
                        <td>{record.ip_address || '-'}</td>
                        <td className="user-agent">{record.user_agent || '-'}</td>
                        <td>
                          <span className={`status ${record.status}`}>
                            {record.status === 'success' ? '成功' : '失败'}
                          </span>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              <div className="pagination">
                <button 
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage(prev => prev - 1)}
                >
                  上一页
                </button>
                <span>{currentPage} / {loginRecords.total_pages}</span>
                <button 
                  disabled={currentPage === loginRecords.total_pages}
                  onClick={() => setCurrentPage(prev => prev + 1)}
                >
                  下一页
                </button>
              </div>
            </div>
          )}

          {/* 数据处理记录 */}
          {activeTab === 'processing-records' && (
            <div className="records-section">
              <div className="filters">
                <input
                  type="text"
                  placeholder="用户名"
                  value={filters.username}
                  onChange={(e) => handleFilterChange('username', e.target.value)}
                />
                <input
                  type="text"
                  placeholder="操作类型"
                  value={filters.operation_type}
                  onChange={(e) => handleFilterChange('operation_type', e.target.value)}
                />
                <input
                  type="date"
                  placeholder="开始日期"
                  value={filters.start_date}
                  onChange={(e) => handleFilterChange('start_date', e.target.value)}
                />
                <input
                  type="date"
                  placeholder="结束日期"
                  value={filters.end_date}
                  onChange={(e) => handleFilterChange('end_date', e.target.value)}
                />
                <select
                  value={filters.status}
                  onChange={(e) => handleFilterChange('status', e.target.value)}
                >
                  <option value="">所有状态</option>
                  <option value="success">成功</option>
                  <option value="failed">失败</option>
                  <option value="processing">处理中</option>
                </select>
              </div>
              
              <div className="records-table">
                <table>
                  <thead>
                    <tr>
                      <th>用户名</th>
                      <th>操作类型</th>
                      <th>文件名</th>
                      <th>处理时间</th>
                      <th>耗时</th>
                      <th>状态</th>
                      <th>错误信息</th>
                    </tr>
                  </thead>
                  <tbody>
                    {processingRecords.items.map(record => (
                      <tr key={record.id}>
                        <td>{record.username}</td>
                        <td>{record.operation_type}</td>
                        <td className="filename">{record.file_name || '-'}</td>
                        <td>{formatDateTime(record.processing_time)}</td>
                        <td>{formatDuration(record.duration_ms)}</td>
                        <td>
                          <span className={`status ${record.status}`}>
                            {record.status === 'success' ? '成功' : 
                             record.status === 'failed' ? '失败' : '处理中'}
                          </span>
                        </td>
                        <td className="error-message">{record.error_message || '-'}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
              
              <div className="pagination">
                <button 
                  disabled={currentPage === 1}
                  onClick={() => setCurrentPage(prev => prev - 1)}
                >
                  上一页
                </button>
                <span>{currentPage} / {processingRecords.total_pages}</span>
                <button 
                  disabled={currentPage === processingRecords.total_pages}
                  onClick={() => setCurrentPage(prev => prev + 1)}
                >
                  下一页
                </button>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default AdminPanel; 